package icu.wdm.flinkcdc.mysql;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.util.CollectionUtils;
import org.yaml.snakeyaml.Yaml;
import org.springframework.util.StringUtils;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class MySqlDBUtils {

    private static HikariDataSource dataSource;

    public static synchronized void initConnectionPool() {
        if (dataSource != null) {
            System.out.println("连接池已经初始化");
            return;
        }
        try (InputStream inputStream = MySqlDBUtils.class.getClassLoader().getResourceAsStream("application.yml")) {
            if (inputStream == null) {
                throw new IllegalArgumentException("application.yml not found!");
            }
            Yaml yaml = new Yaml();
            Map<String, Object> config = yaml.load(inputStream);
            Map<String, String> sinkConfig = (Map<String, String>) ((Map<String, String>) config.get("sink"));

            String url = (String) sinkConfig.get("url");
            String username = String.valueOf(sinkConfig.get("username"));
            String password = String.valueOf(sinkConfig.get("password"));
            String driverName = String.valueOf(sinkConfig.get("driverName"));

            if (StringUtils.isEmpty(url) || StringUtils.isEmpty(username) || StringUtils.isEmpty(password) || StringUtils.isEmpty(driverName)) {
                throw new IllegalArgumentException("source参数异常");
            }

            // 初始化连接池
            HikariConfig hikariConfig = new HikariConfig();
            hikariConfig.setJdbcUrl(url);
            hikariConfig.setUsername(username);
            hikariConfig.setPassword(password);
            hikariConfig.setDriverClassName(driverName);

            // Optional: Configure additional HikariCP settings
            hikariConfig.setMaximumPoolSize(10);
            hikariConfig.setMinimumIdle(2);
            hikariConfig.setIdleTimeout(30000);
            hikariConfig.setMaxLifetime(1800000);
            hikariConfig.setConnectionTimeout(30000);

            dataSource = new HikariDataSource(hikariConfig);
        } catch (Exception e) {
            throw new RuntimeException("连接池加载出错", e);
        }
    }

    // 关闭连接池
    public static synchronized void closeConnectionPool() {
        if (dataSource != null) {
            dataSource.close();
            dataSource = null;
        }
    }

    public static int executeSql(String sql, List<Object> insertParams, List<Object> updateParams) throws SQLException {
        if (StringUtils.isEmpty(sql)) {
            return 0;
        }
        try (Connection conn = dataSource.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {

            // 设置INSERT部分的参数
            if(!CollectionUtils.isEmpty(insertParams)&&!CollectionUtils.isEmpty(updateParams)){
                for (int i = 0; i < insertParams.size(); i++) {
                    ps.setObject(i + 1, insertParams.get(i));
                }

                // 设置ON DUPLICATE KEY UPDATE部分的参数
                for (int i = 0; i < updateParams.size(); i++) {
                    ps.setObject(insertParams.size() + i + 1, updateParams.get(i));
                }
            }
            return ps.executeUpdate();
        } catch (SQLException e) {
            throw e;
        }
    }
}